from django.db import models
from django.contrib.auth.models import User

# models
class Stock(models.Model):
    symbol = models.CharField(max_length=8, primary_key=True)
    description = models.CharField(max_length=20, blank=True, null=True)

class Player(models.Model):
    """The main player. An alternative way of doing this would be extending the User model, which is recommended by the docs (https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project).
    Here we opt for using a model with the User as a ForeignKey to make this as plug-and-play as possible. Extending the User model would require everyone who wants to embed zylinder_app into their project to also extend their model. While this could be done with requiring some field (e.g. zylinder_app_capital), this way is easier for both sides.
    """
    # CASCADE -> delete entry when ForeignKey gets deleted
    djangouser = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    alias = models.CharField(max_length=20)
    startcapital = models.IntegerField()
    capital = models.IntegerField()
    # hack to save only 0 to 99 -> integerfield can have digits reqs only with a validator
    acceptedloss = models.DecimalField(max_digits=2, decimal_places=0) 
    lost = models.BooleanField(default=False)
    # save lostcapital as times ten, to avoid decimalfield
    # decimalfield requires a max_digits, integerfield does not
    lostcapitaltimesten = models.IntegerField(blank=True, null=True)

class Transaction(models.Model):
    transnr = models.IntegerField(primary_key=True)
    player = models.ForeignKey(Player, on_delete=models.CASCADE)
    # when a stock gets deleted the according transactions get deleted
    symbol = models.ForeignKey(Stock, on_delete=models.PROTECT)
    buydate = models.DateTimeField(auto_now_add=True)
    boughtfor = models.DecimalField(max_digits=6, decimal_places=2)
    selldate = models.DateTimeField(blank=True, null=True)
    soldfor = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)

